package com.platform.auth.controller;

import com.alibaba.fastjson.JSON;
import com.platform.auth.cache.PoolCache;
import com.platform.auth.config.Constants;
import com.platform.auth.constant.MessageMouldContants;
import com.platform.auth.form.AppLoginBody;
import com.platform.auth.form.LoginBody;
import com.platform.auth.form.LoginPhoneBody;
import com.platform.auth.form.ScanLoginBody;
import com.platform.auth.model.dto.ResultDto;
import com.platform.auth.model.vo.QRCodeInfo;
import com.platform.auth.service.SysLoginService;
import com.platform.common.core.constant.CacheConstants;
import com.platform.common.core.constant.SecurityConstants;
import com.platform.common.core.constant.UserConstants;
import com.platform.common.core.domain.R;
import com.platform.common.core.domain.entity.PlatApp;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.JwtUtils;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.redis.service.RedisService;
import com.platform.common.security.auth.AuthUtil;
import com.platform.common.security.service.TokenService;
import com.platform.common.security.utils.RsaUtils;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.message.api.remote.api.RemoteMessageService;
import com.platform.message.api.remote.vo.MsgpoolVO;
import com.platform.miniprogram.api.remote.api.RemoteMiniprogramService;
import com.platform.miniprogram.api.remote.vo.UserLoginDTO;
import com.platform.usercenter.api.remote.api.RemoteUserService;
import com.platform.usercenter.api.remote.dto.SysUserGuest;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 *
 * @author
 */
@RestController
public class TokenController {

	private static final Logger log=LoggerFactory.getLogger( TokenController.class );
	@Autowired
	private TokenService tokenService;

	@Autowired
	private SysLoginService sysLoginService;

	@Autowired
	private RedisService redisService;

	@Autowired
	private RemoteUserService remoteUserService;
	@Autowired
	private RemoteMessageService messageService;
	@Autowired
	private RemoteMiniprogramService miniprogramService;

	private Long expireTime=CacheConstants.PHONECODE_TIME;
	private final static String ACCESS_TOKEN=CacheConstants.LOGIN_TOKEN_KEY;

	/**
	 * 外部应用登录
	 */
	@PostMapping("appLogin")
	public R< ? > appLogin( @RequestBody AppLoginBody form ) {
		PlatApp platApp=sysLoginService.appLogin( form.getAppKey( ),form.getAppSecret( ) );
		return R.ok( tokenService.createToken( platApp ) );
	}

	@PostMapping("newAppLogin")
	public R< ? > newAppLogin( @RequestBody LoginBody form,HttpServletRequest request ) {

		String pwd=null;
		// 用户登录
		LoginUser userInfo=null;
		try {
			pwd=RsaUtils.decryptByPrivateKey( form.getPassword( ) );
		} catch(Exception e) {
			log.error( "登录异常",e );
			return R.fail( e.getMessage( ) );
		}
		userInfo=sysLoginService.login( form.getUsername( ),pwd,request );
		//判断登录端
		String userkey=userInfo.getSysUser( ).getUserId( ).toString( )+form.getFlag( );
		userInfo.setFlag( form.getFlag( ) );
//            String token = redisService.getCacheObject(UserConstants.VERSION_PRE + userkey);
//            if (token != null) {
//                boolean b = redisService.deleteObject(ACCESS_TOKEN + token);
//                System.out.println(b);
//            }
		// 获取登录token
		//接入在线监控
		redisService.setCacheObject( CacheConstants.APP_ONLINE_DIR+userInfo.getSysUser( ).getUserId( ),userInfo );
		return R.ok( tokenService.createToken( userInfo ) );
	}

	@PostMapping("login")
	public R< ? > login( @RequestBody LoginBody form,HttpServletRequest request ) {

		String pwd=null;
		// 用户登录
		LoginUser userInfo=null;
		try {
			pwd=RsaUtils.decryptByPrivateKey( form.getPassword( ) );
		} catch(Exception e) {
			log.error( "登录异常",e );
			return R.fail( e.getMessage( ) );
		}
		log.info( "PC端的Flag---------------------->"+form.getFlag() );
		userInfo=sysLoginService.login( form.getUsername( ),pwd,request );
		//判断登录端
		String userkey=userInfo.getSysUser( ).getUserId( ).toString( )+form.getFlag( );
		userInfo.setFlag( form.getFlag( ) );
//            String token = redisService.getCacheObject(UserConstants.VERSION_PRE + userkey);
//            if (token != null) {
//                boolean b = redisService.deleteObject(ACCESS_TOKEN + token);
//                System.out.println(b);
//            }
		// 获取登录token
		return R.ok( tokenService.createToken( userInfo ) );
	}

	@PostMapping("wxLogin")
	public R< ? > wxLogin( @RequestBody LoginPhoneBody form,HttpServletRequest request ) {
		if(StringUtils.isEmpty( form.getMarkCode( ) )) {
			return R.fail( "唯一性code不能为空！" );
		}
		//获取openid
		String openId=getOpenid( form.getMarkCode( ) );
		if(StringUtils.isEmpty( openId )) {
			return R.fail( "解析openid失败！" );
		}
		//根据openId获取用户信息
		log.info( "调用用户中心，根据openId查询用户信息，参数：openId："+openId );
		R< LoginUser > loginUserR=null;
		LoginUser user=null;
		try {
			loginUserR=remoteUserService.selectByOpenId( openId,SecurityConstants.INNER );
			if(R.SUCCESS==loginUserR.getCode( )) {
				if(ObjectUtils.isEmpty( loginUserR.getData( ) )) {
					return R.ok( );//无token
				}else {
					user=loginUserR.getData( );
					user.setFlag( form.getFlag( ) );
					user.setLoginUserType(Constants.USER_TYPE_01);
				}
			}else {
				log.error( "调用用户中心，根据openId查询用户信息异常" );
				return R.fail( "登录异常,请联系管理员" );
			}
		} catch(Exception e) {
			log.error( "登录异常,请联系管理员",e );
			return R.fail( e.getMessage( ) );
		}
		//wx登录在线监控
		redisService.setCacheObject( CacheConstants.WCHAT_ONLINE_DIR+user.getSysUser( ).getUserId( ),user );
		return R.ok( tokenService.createToken( user ) );
	}

	/**
	 * 保存游客的手机号码
	 * @param form
	 * @return
	 */
	@PostMapping("guestAddPhone")
	public R< ? > guestAddPhone( @RequestBody LoginPhoneBody form ) {
		if(StringUtils.isEmpty( form.getPhone( ) )) {
			return R.fail( "手机号不能为空！" );
		}
		if(StringUtils.isEmpty( form.getCode( ) )) {
			return R.fail( "手机验证码不能为空！" );
		}
		if(StringUtils.isEmpty( form.getOpenid( ) )) {
			return R.fail( "唯一性Openid不能为空！" );
		}
		//校验验证码
		String getPhoneCode=redisService.getCacheObject( getCacheKey( form.getPhone( ) ) );
		if(getPhoneCode==null || !getPhoneCode.equals( form.getCode( ) )) {
			return R.fail( "手机验证码错误或则过期" );
		}
		SysUserGuest queryGuest = new SysUserGuest();
		queryGuest.setMarkCode(form.getOpenid());
		queryGuest.setPhonenumber(form.getPhone());
		R<Integer> edtR = remoteUserService.editUserGuest(queryGuest, SecurityConstants.INNER);
		if(R.SUCCESS==edtR.getCode()) {
			return R.ok();
		}else {
			return R.fail( "游客电话号码添加失败" );
		}
	}

	/**
		 * 小程序游客登录
	 * @param form
	 * @param request
	 * @return
	 */
	@PostMapping("wxTouristLogin")
	public R< ? > wxTouristLogin( @RequestBody LoginPhoneBody form,HttpServletRequest request ) {
		if(StringUtils.isEmpty( form.getMarkCode( ) )) {
			return R.fail( "唯一性code不能为空！" );
		}
		//获取openid
		String openId=getOpenid(form.getMarkCode());
		if(StringUtils.isEmpty( openId )) {
			return R.fail( "解析openid失败！" );
		}
		String phoneNumber=form.getPhone();
		LoginUser user = new LoginUser();
		user.setFlag( form.getFlag( ) );
		user.setLoginUserType(Constants.USER_TYPE_02);
		SysUser sysUser = new SysUser();
		sysUser.setPhonenumber(form.getPhone());
		sysUser.setOpenId(openId);
		user.setSysUser(sysUser);

		// 根据openId查询游客历史是否有登录信息
		SysUserGuest queryGuest = new SysUserGuest();
		queryGuest.setType("WX");
		queryGuest.setMarkCode(openId);
		queryGuest.setDelFlag("0");
		R<List<SysUserGuest>> guestR = remoteUserService.getGuestInfo(queryGuest,SecurityConstants.INNER);
		if(R.SUCCESS==guestR.getCode()) {
			if(ObjectUtils.isEmpty(guestR.getData())) {
				// 新增
				queryGuest.setName("游客"+UUID.randomUUID().toString().replaceAll("-","").substring(0,8));
				queryGuest.setPhonenumber(form.getPhone());
				R<Long> addR = remoteUserService.addUserGuest(queryGuest,SecurityConstants.INNER);
				if(R.SUCCESS==addR.getCode()) {
					queryGuest.setUserId(addR.getData());
				}else {
					return R.fail( "登录异常,请联系管理员" );
				}
				}else {
				queryGuest=guestR.getData().get(0);
				sysUser.setUserName(queryGuest.getName());
				sysUser.setPhonenumber(queryGuest.getPhonenumber());
				phoneNumber=queryGuest.getPhonenumber();
			}
			sysUser.setUserId(queryGuest.getUserId());
		}else {
			log.error( "调用用户中心，根据openId查询用户信息异常" );
			return R.fail( "登录异常,请联系管理员" );
		}
		//wx登录在线监控
		redisService.setCacheObject(CacheConstants.WCHAT_ONLINE_DIR+form.getMarkCode(),user);
		Map<String, Object> reponseMap = tokenService.createToken(user);
		reponseMap.put("phoneNumber",phoneNumber);
		reponseMap.put("openId",openId);
		return R.ok(reponseMap);
	}

	/**
	 * 根据token获取用户类型
	 * @return
	 */
	@GetMapping("getUserType")
	public AjaxResult getUserType(){
		LoginUser loginUser = SecurityUtils.getLoginUser();
		if(ObjectUtils.isNotEmpty(loginUser)){
			return AjaxResult.success("获取用户类型成功！",loginUser);
		}else {
			return AjaxResult.error("获取用户token异常！");
		}
	}



	@PostMapping("bindOpenid")
	public R< ? > bindOpenid( @RequestBody LoginPhoneBody form,HttpServletRequest request ) {
		if(StringUtils.isEmpty( form.getPhone( ) )) {
			return R.fail( "手机号不能为空！" );
		}
		if(StringUtils.isEmpty( form.getCode( ) )) {
			return R.fail( "手机验证码不能为空！" );
		}
		if(StringUtils.isEmpty( form.getMarkCode( ) )) {
			return R.fail( "唯一性code不能为空！" );
		}
		//校验验证码
		String getPhoneCode=redisService.getCacheObject( getCacheKey( form.getPhone( ) ) );
		if(getPhoneCode==null || !getPhoneCode.equals( form.getCode( ) )) {
			return R.fail( "手机验证码错误或则过期" );
		}

		//获取openid
		String openId=getOpenid( form.getMarkCode( ) );
		if(StringUtils.isEmpty( openId )) {
			return R.fail( "获取openid失败！" );
		}
		//用户绑定
		log.info( "调用用户中心，用户绑定openid，参数：openId："+openId+"，phone："+form.getPhone( ) );
		LoginUser user=null;
		try {
			R< LoginUser > result=remoteUserService.bindOpenid( form.getPhone( ),openId,SecurityConstants.INNER );
			if(R.SUCCESS==result.getCode( ) && ObjectUtils.isNotEmpty( result.getData( ) )) {//绑定成功
				user=result.getData( );
			}else {
				log.error( "调用用户中心，用户绑定openid异常！" );
				return R.fail( "非工作人员暂未开放登录 请联系管理员~" );
			}
		} catch(Exception e) {
			log.error( "用户绑定异常",e );
			return R.fail( e.getMessage( ) );

		}
		return R.ok( tokenService.createToken( user ) );
	}

	private String getOpenid( String markCode ) {
		UserLoginDTO userLoginDTO=new UserLoginDTO( );
		userLoginDTO.setCode( markCode );
		log.info( "调用微信服务，获取openid参数："+JSON.toJSONString( userLoginDTO ) );
		R< String > openidResult=miniprogramService.getOpenid( userLoginDTO,SecurityConstants.INNER );
		String openId="";
		if(R.SUCCESS==openidResult.getCode( ) && ObjectUtils.isNotEmpty( openidResult.getData( ) )) {
			openId=openidResult.getData( );
		}
		return openId;
	}

	@PostMapping("unbindOpenid")
	public R< ? > unbindOpenid( @RequestBody LoginPhoneBody form,HttpServletRequest request ) {
		if(StringUtils.isEmpty( form.getPhone( ) )) {
			return R.fail( "手机号不能为空！" );
		}
		if(StringUtils.isEmpty( form.getCode( ) )) {
			return R.fail( "手机验证码不能为空！" );
		}
		//校验验证码
		String getPhoneCode=redisService.getCacheObject( getCacheKey( form.getPhone( ) ) );
		if(getPhoneCode==null || !getPhoneCode.equals( form.getCode( ) )) {
			return R.fail( "手机验证码错误或则过期" );
		}
		//用户解绑定
		log.info( "调用用户中心，用户解绑定openid，参数：phone："+form.getPhone( ) );
		LoginUser user=null;
		try {
			R< Boolean > result=remoteUserService.unbindOpenid( form.getPhone( ),form.getOpenid( ),SecurityConstants.INNER );
			if(R.SUCCESS==result.getCode( ) && result.getData( )) {//解绑成功
				String token=SecurityUtils.getToken( request );
				if(StringUtils.isNotEmpty( token )) {//清除token
					tokenService.delLoginUser( token );
				}
			}else {
				log.error( result.getMsg( ) );
				return R.fail( "解绑异常！" );
			}
		} catch(Exception e) {
			log.error( "用户绑定异常",e );
			return R.fail( e.getMessage( ) );
		}
		return R.ok( );
	}

	@DeleteMapping("logout")
	public R< ? > logout( HttpServletRequest request,String flag ) {
		String token=SecurityUtils.getToken( request );
		if(StringUtils.isNotEmpty( token )) {
			tokenService.delLoginUser( token );
			String username=JwtUtils.getUserName( token );
//            // 查询用户信息
//            R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
//            SysUser user = userResult.getData().getSysUser();
//            //删除设备标记
//            redisService.deleteObject(UserConstants.VERSION_PRE+user.getUserId()+flag);
			// 删除用户缓存记录
			AuthUtil.logoutByToken( token );
			// 记录用户退出日志
			sysLoginService.logout( username );
		}
		return R.ok( );
	}

	@PostMapping("refresh")
	public R< ? > refresh( HttpServletRequest request ) {
		LoginUser loginUser=tokenService.getLoginUser( request );
		if(StringUtils.isNotNull( loginUser )) {
			// 刷新令牌有效期
			tokenService.refreshToken( loginUser );
			return R.ok( );
		}
		return R.ok( );
	}

	/**
	 * 20230417 BY ZHULU 不允许系统存在注册接口
	 */
	//    @PostMapping("register")
//    public R<?> register(@RequestBody RegisterBody registerBody) {
//        // 用户注册
//        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
//        return R.ok();
//    }


	/**
	 * 外部系统跳转 获取临时 token
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("createRedirectToken")
	public R< ? > createRedirectToken( HttpServletRequest request ) {
		LoginUser loginUser=tokenService.getLoginUser( request );
		return R.ok( tokenService.createRedirectToken( loginUser ) );
	}


	/**
	 * 根据 redirectToken获取用户登录 token
	 *
	 * @param redirectToken
	 * @return
	 */
	@PostMapping("getRedirectToken")
	public R< ? > getRedirectToken( @RequestParam(value="redirectToken") String redirectToken ) {
		return R.ok( tokenService.getRedirectToken( redirectToken ) );
	}


	/**
	 * 根据手机号登录
	 *
	 * @author yzg
	 * @date 18:12 2023/1/30
	 **/
	@PostMapping("/byPhoneLogin")
	public R< ? > byPhoneLogin( @RequestBody LoginPhoneBody loginPhoneBody,HttpServletRequest request ) {

		if(StringUtils.isAnyBlank( loginPhoneBody.getPhone( ),loginPhoneBody.getCode( ) )) {
			throw new ServiceException( "账号/验证码必须填写" );
		}
		String getPhoneCode=redisService.getCacheObject( getCacheKey( loginPhoneBody.getPhone( ) ) );
		if(getPhoneCode==null || !getPhoneCode.equals( loginPhoneBody.getCode( ) )) {
			throw new ServiceException( "手机验证码错误或则过期" );

		}
		LoginUser userInfo=null;
		userInfo=sysLoginService.loginByphone( loginPhoneBody.getPhone( ),request );
		//判断登录端
		String userkey=userInfo.getSysUser( ).getUserId( ).toString( )+loginPhoneBody.getFlag( );
		userInfo.setFlag( loginPhoneBody.getFlag( ) );
		// 获取登录token
		return R.ok( tokenService.createToken( userInfo ) );
	}


	/**
	 * 获取手机验证码
	 *
	 * @author yzg
	 * @date 17:19 2023/1/30
	 **/
	@PostMapping("byPhoneCode")
	public R< ? > byPhoneCode( @RequestBody LoginPhoneBody phoneBody ) {
		if(StringUtils.isEmpty( phoneBody.getPhone( ) )) {
			return R.fail( "参数有误！" );
		}
		Boolean flag=redisService.hasKey( getCacheKey( phoneBody.getPhone( ) ) );
		if(flag) {
			//验证码未过期——禁止重复访问
			return R.fail( "验证码尚在有效期内，请勿重复获取！" );
		}
		String userName="";
		if(!"wx".equals( phoneBody.getFlag( ) )) {
			// 查询用户信息
			R< LoginUser > userResult=remoteUserService.infoByPhonenumber( phoneBody.getPhone( ),SecurityConstants.INNER );

			if(StringUtils.isNull( userResult ) || StringUtils.isNull( userResult.getData( ) )) {
				return R.fail( "登录用户："+phoneBody.getPhone( )+" 不存在" );
			}
			try {
				userName=userResult.getData( ).getSysUser( ).getNickName( );
			} catch(Exception e) {
				log.error( "获取用户昵称异常" );
			}
		}
		String yzmCode=StringUtils.getRandomNum( );
		//调用获取验证码接口
		MsgpoolVO msgpoolVO=new MsgpoolVO( );
		//接收对象
		msgpoolVO.setMsgReceiver( phoneBody.getPhone( ) );
		msgpoolVO.setMsgType( MessageMouldContants.MSG_TYPE.MESSAGE );
		msgpoolVO.setTcode( MessageMouldContants.DataType.SMS_TEMPLATE_CODE );
		msgpoolVO.setMsgTitle( "认证中心-登录验证码" );
		msgpoolVO.setSender( userName );

		Map< String, String > params=new HashMap<>( );
		params.put( MessageMouldContants.JSON_PARAM_CODE,yzmCode );
		msgpoolVO.setMsgParams( params );

		//调用获取短信验证码接口
		R< String > sendResult=messageService.msgSend( msgpoolVO,SecurityConstants.INNER );
		if(R.SUCCESS==sendResult.getCode( )) {
			redisService.setCacheObject( getCacheKey( phoneBody.getPhone( ) ),yzmCode,expireTime,TimeUnit.MINUTES );
			return R.ok( );
		}
		return R.fail( );
	}

	private String getCacheKey( String username ) {
		return CacheConstants.PHONE_CAPTCHA_CODE_KEY+username;
	}

	/**
	 * 生成uuid
	 *
	 * @return
	 */
	@PostMapping("generate")
	@ResponseBody
	public ResultDto generate( ) {
		String uuid=null;
		try {
			uuid=initQRCodeInfo( );
		} catch(Exception e) {
			log.error( "Generate uuid of QR code error!",e );
		}
		if(null==uuid) {
			return new ResultDto<>( false,null,"Generate uuid of QR code error!" );
		}
		return new ResultDto<>( true,uuid,"Generate uuid of QR code successfully!" );
	}

	/**
	 * 初始化二维码信息，并添加至缓存池
	 *
	 * @return uuid
	 */
	private String initQRCodeInfo( ) {
		String uuid=UUID.randomUUID( ).toString( ).replaceAll( "-","" );
		redisService.setCacheObject( uuid,new QRCodeInfo( Constants.QRCodeStatus.NOT_SCAN ),1L,TimeUnit.MINUTES );
		return uuid;
	}

	/**
	 * 轮询检查
	 *
	 * @param scanLoginBody
	 * @return
	 */
	@PostMapping("checkByPool")
	@ResponseBody
	public ResultDto checkByPool( @RequestBody ScanLoginBody scanLoginBody ) {
		ResultDto< QRCodeInfo > resultDto=new ResultDto<>( );
		if(scanLoginBody==null || StringUtils.isEmpty( scanLoginBody.getUuid( ) )) {
			resultDto.setFlagAndMsg( false,"The parameter is null while pooling!" );
			log.warn( "轮询时，输入参数uuid为空！" );
			return resultDto;
		}

		boolean flag=false;
		log.info( MessageFormat.format( "查询二维码状态（{0}），检测是否登录。",scanLoginBody.getUuid( ) ) );
		QRCodeInfo qrCodeInfo=(QRCodeInfo) redisService.getCacheObject( scanLoginBody.getUuid( ) );
		if(null!=qrCodeInfo && Constants.QRCodeStatus.SCANNED.equals( qrCodeInfo.getStatus( ) )) {
			qrCodeInfo.setStatus( Constants.QRCodeStatus.SCANNED );
			qrCodeInfo.setToken( qrCodeInfo.getToken( ) );
			flag=true;
			redisService.deleteObject( scanLoginBody.getUuid( ) );
		}
		resultDto.setFlagAndData( flag,qrCodeInfo );
		return resultDto;
	}


	ResultDto< QRCodeInfo > resultDto=new ResultDto<>( );

	/**
	 * 扫码操作
	 *
	 * @param scanLoginBody
	 * @return
	 */
	@PostMapping("scan")
	@ResponseBody
	public R< T > scan( @RequestBody ScanLoginBody scanLoginBody ) {
		ResultDto< QRCodeInfo > resultDto=new ResultDto<>( );
		if(null==scanLoginBody.getUuid( ) || 0==scanLoginBody.getUuid( ).length( )) {
			resultDto.setFlagAndMsg( false,"The parameter is null while scanning!" );
			log.warn( "扫码时，传入参数uuid为空！" );
			return R.fail( "参数异常" );
		}
		if(StringUtils.isEmpty( scanLoginBody.getOpenId( ) )) {
			return R.fail( "缺少Openid参数！" );
		}
		//根据openid生成token
		R< LoginUser > watchService=remoteUserService.selectByOpenId( scanLoginBody.getOpenId( ),MessageMouldContants.FROM_SOURCE );
		LoginUser userInfo=watchService.getData( );
		if(ObjectUtils.isEmpty( userInfo )) {
			return R.fail( "未绑定小程序！" );
		}
		String userkey=userInfo.getSysUser( ).getUserId( ).toString( )+Constants.PC_FLAG;
		log.info( "PC端扫码登录的userkey------->"+userkey );
		userInfo.setFlag( Constants.PC_FLAG );
		log.info( "登录的端"+userInfo.getFlag( ) );
		String oldToken=redisService.getCacheObject( UserConstants.VERSION_PRE+userkey );
		log.info( "获取到的老的token"+oldToken );
		if(oldToken!=null) {
			boolean b=redisService.deleteObject( ACCESS_TOKEN+oldToken );
			log.info( "删除结果"+b );
		}
		//生成token
		Map< String, Object > tokenMap=tokenService.createToken( userInfo );
		String token=(String) tokenMap.get( "access_token" );
		log.info( MessageFormat.format( "扫描二维码（{0}）进行登录操作。",scanLoginBody.getUuid( ) ) );
		QRCodeInfo qrCodeInfo=(QRCodeInfo) redisService.getCacheObject( scanLoginBody.getUuid( ) );
		try {
			if(null==qrCodeInfo) { // uuid对应数据为空，二维码失效
				log.info( MessageFormat.format( "该二维码（{0}）已失效！",scanLoginBody.getUuid( ) ) );
				return R.fail( "二维码失效" );
			}else {
				qrCodeInfo.setStatus( Constants.QRCodeStatus.SCANNED ); // 更新二维码状态
				qrCodeInfo.setToken( token );
				redisService.setCacheObject( scanLoginBody.getUuid( ),qrCodeInfo );
			}
		} catch(Exception e) {
			log.error( MessageFormat.format( "Scan error! <uuid:${0}, tabId:{1}>",scanLoginBody.getUuid( ) ),e );
			return R.fail( "Scan error!" );
		}
		return R.ok( );
	}

	/**
	 * 根据uuid，获取session数据（含用户信息）
	 *
	 * @param uuid
	 * @return
	 */
	private String getSessionByUuid( @RequestBody String uuid ) {
		return "The session data of "+uuid;
	}

	/**
	 * 扫码登录成功跳转
	 *
	 * @return
	 */
	@PostMapping("scanSuccess")
	@ResponseBody
	public String scanSuccess( ) {
		return "扫码登录成功！";
	}


}
